package ren.steve.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import ren.steve.annotation.Log;
import ren.steve.common.result.HttpStatus;
import ren.steve.common.result.Result;
import ren.steve.common.utils.FormatDateUtil;
import ren.steve.enums.BusinessType;
import ren.steve.model.system.bean.SystemRole;
import ren.steve.model.system.bean.SystemRoleMenu;
import ren.steve.model.system.vo.SystemRoleQueryVo;
import ren.steve.system.service.SystemMenuService;
import ren.steve.system.service.SystemRoleMenuService;
import ren.steve.system.service.SystemRoleService;

import java.util.*;

/**
 * @Author: LiuGuoJia
 * @Description:
 * @Date: Created in 2024/1/18 16:23
 * @URL: http://127.0.0.1:9900/api/system/system-role
 * @SwaggerURL: http://127.0.0.1:9900/doc.html
 */

@Api(tags = "APIs-角色管理")
@CrossOrigin
@RestController
@RequestMapping("/api/system/system-role")
public class SystemRoleController {

  @Autowired
  private SystemRoleService systemRoleService;

  @Autowired
  private SystemMenuService systemMenuService;

  @Autowired
  private SystemRoleMenuService systemRoleMenuService;

  @ApiOperation("API-查询所有")
  @Log(title = "查询所有", businessType = BusinessType.GET)
  @PreAuthorize("hasAuthority('/api/system/system-role/list')")
  @GetMapping("list")
  public Result findList () {
    List<SystemRole> roles = systemRoleService.list();
    return Result.ok(roles, HttpStatus.OK);
  }

  @ApiOperation("API-根据ID查询单条数据")
  @Log(title = "根据ID查询单条数据", businessType = BusinessType.GET)
  @PreAuthorize("hasAuthority('/api/system/system-role/detail')")
  @GetMapping("detail")
  public Result findById (String id) {
    SystemRole role = systemRoleService.getById(id);
    QueryWrapper<SystemRoleMenu> wrapper = new QueryWrapper<>();
    wrapper.eq("role_id", id);
    List<SystemRoleMenu> roleMenus = systemRoleMenuService.list(wrapper);
    Map<String, Object> map = new HashMap<>();
    List<String> menus = new ArrayList<>();
    for (SystemRoleMenu menu : roleMenus) {
      menus.add(menu.getMenuId());
    }
    map.put("menus", menus);
    role.setParams(map);
    return Result.ok(role, HttpStatus.OK);
  }

  @ApiOperation("API-条件分页查询")
  @Log(title = "角色分页查询", businessType = BusinessType.GET)
  @PreAuthorize("hasAuthority('/api/system/system-role/list/query')")
  @GetMapping("list/query")
  public Result findListPage (SystemRoleQueryVo vo) {
    // 创建配置对象
    int page = 1;
    int pageSize = 20;
    if (vo.getPage() != null) {
      page = vo.getPage();
    }
    if (vo.getPageSize() != null) {
      pageSize = vo.getPageSize();
    }
    Page<SystemRole> pagination = new Page<>(page, pageSize);
    // 调用 Service 方法
    IPage<SystemRole> model = systemRoleService.select(pagination, vo);
    return Result.ok(model, HttpStatus.OK);
  }

  @ApiOperation("API-添加一条数据")
  @Log(title = "角色添加", businessType = BusinessType.INSERT)
  @PreAuthorize("hasAuthority('/api/system/system-role/save')")
  @PostMapping("save")
  public Result save (@RequestBody SystemRole role) {
    role.setGmtCreate(FormatDateUtil.helperFormatDate("yyyy-MM-dd HH:mm:ss", new Date()));
    role.setGmtUpdate(FormatDateUtil.helperFormatDate("yyyy-MM-dd HH:mm:ss", new Date()));
    boolean success = systemRoleService.save(role);
    if (success) {
      return Result.ok(null, HttpStatus.OK);
    }
    return Result.fail();
  }

  @ApiOperation("API-修改数据")
  @Log(title = "修改数据", businessType = BusinessType.UPDATE)
  @PreAuthorize("hasAuthority('/api/system/system-role/update')")
  @PostMapping("update")
  public Result update (@RequestBody SystemRole role) {
    role.setGmtUpdate(FormatDateUtil.helperFormatDate("yyyy-MM-dd HH:mm:ss", new Date()));
    boolean success = systemRoleService.updateById(role);
    if (success) {
      return Result.ok(null, HttpStatus.OK);
    }
    return Result.fail();
  }

  @ApiOperation("API-根据ID删除")
  @Log(title = "根据ID删除", businessType = BusinessType.DELETE)
  @PreAuthorize("hasAuthority('/api/system/system-role/delete')")
  @DeleteMapping("delete/{id}")
  public Result deleteById (@PathVariable Long id) {
    boolean success = systemRoleService.removeById(id);
    if (success) {
      return Result.ok(null, HttpStatus.OK);
    }
    return Result.fail();
  }

  @ApiOperation("API-根据多个ID批量删除")
  @Log(title = "根据多个ID批量删除", businessType = BusinessType.DELETE)
  @PreAuthorize("hasAuthority('/api/system/system-role/delete')")
  @DeleteMapping("delete")
  public Result deleteByIds (@RequestBody List<Long> ids) {
    boolean success = systemRoleService.removeByIds(ids);
    if (success) {
      return Result.ok(null, HttpStatus.OK);
    }
    return Result.fail();
  }

  @ApiOperation("API-角色授权")
  @Log(title = "角色授权", businessType = BusinessType.UPDATE)
  @PreAuthorize("hasAuthority('/api/system/system-role/authorization')")
  @PostMapping("authorization")
  public Result authorizationByRoleId (@RequestBody Map<String, Object> map) {
    boolean success = true;
    String roleId = map.get("roleId").toString();
    Object menus = map.get("menus");
    QueryWrapper<SystemRoleMenu> wrapper = new QueryWrapper<>();
    wrapper.eq("role_id", roleId.toString());
    systemRoleMenuService.remove(wrapper);
    if (menus instanceof List) {
      List<String> list = (List<String>) menus;
      for (String menuId : list) {
        SystemRoleMenu roleMenu = new SystemRoleMenu();
        roleMenu.setRoleId(roleId);
        roleMenu.setMenuId(menuId);
        success = systemRoleMenuService.save(roleMenu);
      }
    }
    if (success) {
      return Result.ok(null, HttpStatus.AUTHORIZED_FAIL);
    }
    return Result.fail(HttpStatus.AUTHORIZED_FAIL);
  }
}





